<?php

require_once "core/db.abstract.php";
require_once "helpers/str_helper.php";

class MysqlDb extends Db_Abstract
{
    var $hostname;
    var $username;
    var $password;

    public function MysqlDb ($hostname = '127.0.0.1', $username = 'root', $password = '') {
        $this->hostname = $hostname;
        $this->username = $username;
        $this->password = $password;
        Db_Abstract::Db_Abstract();
    }

    public function connect () {
        $this->res = mysql_connect($this->hostname, $this->username, $this->password);
        return $this->checkConnection();
    }

    public function close () {
        if ($this->checkConnection()) {
            @mysql_close($this->res);
            $this->res = NULL;
        }
        return true;
    }

    public function selectDb ($db_name) {
        if (!$this->checkConnection()) {
            throw new DbException("invalid resources");
        }
        return mysql_select_db($db_name, $this->res);
    }

    public function fetchSql ($sql) {

        if (!$this->checkConnection()) {
            throw new DbException("invalid resources");
        }
        $result = array();
        $obj = mysql_query($sql);
        if ($obj === False) {
            return $result;
        }
        while ( $row = mysql_fetch_array($obj) ) {
            $tmp_row = array();
            foreach ($row as $k=>$v) {
                if ( !is_integer($k) ) {
                    $tmp_row[$k] = $v;
                }
            }
            array_push($result, $tmp_row);
        }
        return $result;
    }

    public function execSql ($sql) {

        if (!$this->checkConnection()) {
            throw new DbException("invalid resources");
        }
        mysql_query($sql);
    }

    /*
     * $params format:
     *
     *      name string, var mixtype, type string, output boolean
     */
    public function execProc ($procName, $params,  $fetch=False) {
        throw new Exception("my sql not supported execProc.");
    }

    public function _ ($s) {
        return str_replace("'", "''", $s);
    }
    public function __ ($s) {
        return "'" . MysqlDb::_($s) . "'";
    }


}





